package xray

import (
	"fmt"
	"gitee.com/gam6it/SecToolkit/utils/http2"
)

type Template struct {
	client      *Client
	Id          int         `json:"id"`
	Name        string      `json:"name"`
	Remark      string      `json:"remark"`
	TaskSetting TaskSetting `json:"task_setting"`
	CreatedTime string      `json:"created_time"`
}

func newTemplate(c *Client, id int) (*Template, error) {
	var api = fmt.Sprintf("%s%s%d/", c.URI, "api/v2/template/", id)
	var template Template
	err := request(http2.MethodGet, api, c.Token, &template, http2.TimeOut(c.TimeOut))
	template.client = c
	return &template, err
}

func (t *Template) Plans() ([]Plan, error) {
	templateFilter := FilterOption{
		IsPartial: false,
		Content:   t.Name,
	}
	planFilter := PlanFilterOption{
		Limit:            0,
		Offset:           0,
		ProjectID:        t.client.ProjectId,
		TaskTemplateName: []FilterOption{templateFilter},
	}
	_, plans, err := t.client.PlanFilter(planFilter)
	return plans, err
}

// CreatePlan 对某个资产扫描Template创建扫描任务
func (t *Template) CreatePlan(planOption PlanOption) (Plan, error) {
	planOption.TaskTemplateId = t.Id
	planOption.ProjectId = t.client.ProjectId
	if planOption.Priority == "" {
		planOption.Priority = "MEDIUM"
	}
	var plan Plan
	api := t.client.URI + "api/v2/plan/create/"
	err := request(http2.MethodPost, api, t.client.Token, &plan, http2.JsonParam(planOption), http2.TimeOut(t.client.TimeOut))
	return plan, err
}
